package edu.ustb.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import edu.ustb.domain.user.UserAddress;
import edu.ustb.service.user.Impl.UsersServiceImpl;
import edu.ustb.service.user.UsersService;
import edu.ustb.utils.JsonUtil;
import edu.ustb.view.JsonData;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "UserAddressSaveController", value = "/users/addAddress")
public class UserAddressSaveController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain;charset=utf-8");
        //从request域中获得json中的信息
        System.out.println("到达SaveControl");
        PrintWriter out = response.getWriter();
        JSONObject jsonObject = JsonUtil.toJSONOb(request.getInputStream());
        String s = jsonObject.toString();
        UserAddress address = jsonObject.toJavaObject(UserAddress.class);
        System.out.println(address);

        //将数据保存到数据库中
        UsersService usersService = new UsersServiceImpl();
        boolean flag = usersService.insert(address);
        //判断是否保存成功
        if(flag)
        {
            JsonData result = JsonData.success("保存地址成功");
            out.write(JSON.toJSONString(result));
            System.out.println("保存地址成功");
            out.flush();
            out.close();
        }
        else
        {
            JsonData result = JsonData.fail("保存地址成功");
            out.write(JSON.toJSONString(result));
            System.out.println("保存地址失败");
            out.flush();
            out.close();
        }
    }
}
